package org.autumn.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.concurrent.locks.ReentrantLock;

public class ABA {

    // ABA 问题
    static AtomicReference<String> ref = new AtomicReference<>("A");
    // 带版本号 解决ABA问题
    static AtomicStampedReference<String> sref = new AtomicStampedReference<>("A",0);


    public static void main(String[] args) throws InterruptedException {
        String prev = ref.get();
        other();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("A -> C " + ref.compareAndSet(prev,"C"));
    }

    private static void other() {
        String prev = ref.get();
        System.out.println("A -> B " + ref.compareAndSet(prev,"B"));

        prev = ref.get();
        System.out.println("B -> A " + ref.compareAndSet(prev,"A"));
    }
}
